package com.cql.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cql.common.constant.FoodCircleConstant;
import com.cql.common.core.DO.MenuDO;
import com.cql.common.core.DO.UserDO;
import com.cql.common.core.DTO.MaterialDTO;
import com.cql.common.core.DTO.MenuDTO;
import com.cql.common.core.DTO.PictureDTO;
import com.cql.common.core.DTO.StepDTO;
import com.cql.common.exception.menu.MenuNotExistException;
import com.cql.common.utils.StringUtils;
import com.cql.mapper.MenuMapper;
import com.cql.service.business.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cql
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuDO> implements MenuService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private MenuStepService menuStepService;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private SysDictDataService dictDataService;

    @Autowired
    private PictureService pictureService;


    @Override
    public MenuDTO insertMenu(MenuDTO menu, UserDO user) {
        /**
         * 基本信息
         */
        MenuDO menuDO = new MenuDO();
        menuDO.setName(menu.getName());
        menuDO.setTrick(menu.getTrick());
        menuDO.setStatus(menu.getStatus());
        menuDO.setDataScope(menu.getDataScope());
        menuDO.setTime(dictDataService.selectDictLabel(menu.getTime()));
        menuDO.setTaste(dictDataService.selectDictLabel(menu.getTaste()));
        menuDO.setLevel(dictDataService.selectDictLabel(menu.getLevel()));
        menuDO.setMode(dictDataService.selectDictLabel(menu.getMode()));
        menuDO.setTools(dictDataService.listDictLabel(menu.getTools()));
        menuDO.setDescription(menu.getDesc());
        menuDO.setUserId(user.getUserId());
        /**
         * 成品图
         */
        if (StringUtils.isNotNull(menu.getCovers())) {
            List<PictureDTO> covers = menu.getCovers();
            Long[] imgList = new Long[covers.size()];
            for (int i = 0; i < covers.size(); i++) {
                imgList[i] = covers.get(i).getPicId();
            }
            String join = StringUtils.join(imgList, FoodCircleConstant.SEPARATE_CHAR);
            menuDO.setCovers(join);
        }
        menuMapper.insert(menuDO);


        /**
         * 步骤
         */
        List<StepDTO> steps = menu.getSteps();
        /**
         * 批量设置步骤
         */
        menuStepService.insertSteps(steps, menuDO.getMenuId());

        /**
         * 材料：三种材料
         * 1：原料；2：辅料；3：调料
         */
        materialService.insertMaterials(menu.getMainMaterials(), FoodCircleConstant.MAIN_MATERIALS, menuDO.getMenuId());
        materialService.insertMaterials(menu.getAssistMaterials(), FoodCircleConstant.ASSIST_MATERIALS, menuDO.getMenuId());
        materialService.insertMaterials(menu.getOtherMaterials(), FoodCircleConstant.OTHER_MATERIALS, menuDO.getMenuId());

        menu.setMenuId(menuDO.getMenuId());
        return menu;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MenuDTO saveOrUpdate(MenuDTO menu, UserDO user) {

        /**
         * 1.如果存在menuId说明是修改
         */
        if (StringUtils.isNotNull(menu.getMenuId())) {
            this.updateMenu(menu);
            return menu;
        } else {
            // 否则是新增
            MenuDTO menuDTO = this.insertMenu(menu, user);
            return menuDTO;
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteMenu(Long menuId, Long userId) {
        MenuDO menuDO = menuMapper.selectById(menuId);
        /**
         * 1.删除图片
         * 2.删除步骤
         * 3.删除材料
         * 4.删除自身
         * 5.评论
         * 6....
         */

    }

    @Override
    public MenuDTO getMenuById(Long menuId, Long userId) {
        MenuDO menuDO = null;
        QueryWrapper<MenuDO> wrapper = new QueryWrapper<>();
        wrapper.eq("menu_id", menuId);
        if (StringUtils.isNull(userId)) {
            wrapper.eq("user_id", userId);
            menuDO = menuMapper.selectOne(wrapper);
        } else {
            menuDO = menuMapper.selectOne(wrapper);
        }
        if (StringUtils.isNull(menuDO)) {
            throw new MenuNotExistException();
        }

        /**
         * TODO
         * 1.查询基本信息
         * 2.查询步骤
         * 3.查询材料
         */
        MenuDTO menu = new MenuDTO();
        menu.setMenuId(menuDO.getMenuId());
        menu.setName(menuDO.getName());
        menu.setTrick(menuDO.getTrick());
        menu.setDesc(menuDO.getDescription());
        menu.setDataScope(menuDO.getDataScope());
        menu.setStatus(menuDO.getStatus());
        menu.setTaste(dictDataService.getDictCode(menuDO.getTaste()));
        menu.setLevel(dictDataService.getDictCode(menuDO.getLevel()));
        menu.setTime(dictDataService.getDictCode(menuDO.getTime()));
        menu.setMode(dictDataService.getDictCode(menuDO.getMode()));
        // 烹饪工具
        menu.setTools(dictDataService.listDictCode(menuDO.getTools()));

        /**
         * 成品图
         */
        List<PictureDTO> covers = pictureService.listPicture(menuDO.getCovers());
        menu.setCovers(covers);


        /**
         * 步骤
         */
        List<StepDTO> steps = menuStepService.listMenuStep(menuDO.getMenuId());
        menu.setSteps(steps);

        /**
         * 材料
         */
        List<MaterialDTO> mainMaterials = materialService.listMaterial(menuDO.getMenuId(), FoodCircleConstant.MAIN_MATERIALS);
        List<MaterialDTO> otherMaterials = materialService.listMaterial(menuDO.getMenuId(), FoodCircleConstant.OTHER_MATERIALS);
        List<MaterialDTO> assistMaterials = materialService.listMaterial(menuDO.getMenuId(), FoodCircleConstant.ASSIST_MATERIALS);

        menu.setMainMaterials(mainMaterials);
        menu.setOtherMaterials(otherMaterials);
        menu.setAssistMaterials(assistMaterials);


        return menu;
    }

    /**
     * 更新
     *
     * @param menu
     */
    private void updateMenu(MenuDTO menu) {
        /**
         * 需要更新之前的信息：基本信息，步骤，相关图片，材料
         */
        if (StringUtils.isNotNull(menu)) {
            MenuDO menuDO = menuMapper.selectById(menu.getMenuId());
            /**
             * 基本信息
             */
            menuDO.setName(menu.getName());
            menuDO.setTrick(menu.getTrick());
            menuDO.setStatus(menu.getStatus());
            menuDO.setDataScope(menu.getDataScope());
            menuDO.setTime(dictDataService.selectDictLabel(menu.getTime()));
            menuDO.setTaste(dictDataService.selectDictLabel(menu.getTaste()));
            menuDO.setLevel(dictDataService.selectDictLabel(menu.getLevel()));
            menuDO.setMode(dictDataService.selectDictLabel(menu.getMode()));
            menuDO.setTools(dictDataService.listDictLabel(menu.getTools()));
            menuDO.setDescription(menu.getDesc());


            /**
             * 成品图：判断是否需要修改
             */
            List<Long> finishImg = menu.getCovers().stream().map(f -> {
                return f.getPicId();
            }).collect(Collectors.toList());
            String join = StringUtils.join(finishImg, FoodCircleConstant.SEPARATE_CHAR);
            // 设置成品图
            menuDO.setCovers(join);

            menuMapper.updateById(menuDO);

            /**
             * 移除不需要的成品图
             */
            List<Long> removeImg = new ArrayList<>();
            String[] split = menuDO.getCovers().split(FoodCircleConstant.SEPARATE_CHAR);

            for (String s : split) {
                long id = Long.parseLong(s);
                if (!finishImg.contains(id)) {
                    removeImg.add(id);
                }
            }
            // 移除不需要的成品图
            pictureService.deleteImgs(removeImg);


            /**
             * 材料：删除对应的材料，然后新增材料
             */
            materialService.deleteMaterial(menuDO.getMenuId());
            materialService.insertMaterials(menu.getMainMaterials(), FoodCircleConstant.MAIN_MATERIALS, menuDO.getMenuId());
            materialService.insertMaterials(menu.getAssistMaterials(), FoodCircleConstant.ASSIST_MATERIALS, menuDO.getMenuId());
            materialService.insertMaterials(menu.getOtherMaterials(), FoodCircleConstant.OTHER_MATERIALS, menuDO.getMenuId());

            /**
             * 步骤：删除之前的不揍，然后新增
             */
            menuStepService.deleteMenuSteps(menu.getMenuId());
            /**
             * 步骤
             */
            List<StepDTO> steps = menu.getSteps();
            /**
             * 批量设置步骤
             */
            menuStepService.insertSteps(steps, menuDO.getMenuId());

        }

    }


}
